import { Component, OnInit } from '@angular/core';
import { HttpClient } from "@angular/common/http"
import { Router } from "@angular/router"

@Component({
  selector: 'app-siginup',
  templateUrl: './siginup.component.html',
  styleUrls: ['./siginup.component.css']
})

export class SiginupComponent implements OnInit {
  siginupFrom = {
    email: '',
    password: ''
  }

  err_email_msg: string = ''
  
  signup() {
    const fromData = this.siginupFrom
    this.http.post("http://localhost:3000/users",fromData).toPromise().then((data: any)=>{
      this.err_email_msg = ''
      // window.alert("用户注册成功！")
      window.localStorage.setItem("auth_token",data.token)
      window.localStorage.setItem("user_info", JSON.stringify(data.user))
      this.router.navigate(['/']) //跳转到首页
    }).catch(err=>{//捕获异常
      if(err){
        // console.log(err)
        if(err.status == 409) {
          // alert("该用户名已经注册了")
          this.err_email_msg = '邮箱已被占用'
        }
      }
    })
  }

  constructor(
    private http: HttpClient,
    private router: Router
  ) { }

  ngOnInit() {
  }

}
